﻿using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Crownwood.Magic.Common;
using Crownwood.Magic.Docking;
using ProxyHero.Common;
using ProxyHero.HttpUility;
using ProxyHero.Loading;
using ProxyHero.Setting;
using ProxyHero.TabPages;
using System.Net.NetworkInformation;
using LoaMen.Controls;

namespace ProxyHero
{
    public partial class frmMain : Form
    {
        #region  Variable
        delegate void AddNewTabPageCallback(Control control, string Title);
        HttpHelper httpHelper = new HttpHelper();
        delegate void DEnableToolBar(bool enable);
        SplashScreenForm sf = new SplashScreenForm();
        public System.Timers.Timer timerAutoChangeProxy = new System.Timers.Timer();

        #region 定义Docking Manager对象
        private DockingManager DockManager;
        Content ProxyViewContent;
        Content ProxyTestContent;

        #endregion
        #endregion

        #region 网络状态改变
        public void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface n in adapters)
            {
                if (n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                    MsgBox.ShowMessage(string.Format("Changed   {0} is {1}", n.Name, n.OperationalStatus));
            }
            MsgBox.ShowMessage("NetState  :  " + NetHelper.IsConnectedToInternet);
        }

        public void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {
            MsgBox.ShowMessage("IsAvailable  :  " + e.IsAvailable);
            MsgBox.ShowMessage("NetState  :  " + NetHelper.IsConnectedToInternet);

        }
        #endregion

        #region Init
        public frmMain()
        {
            try
            {
                //NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
                //NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);

                this.Hide();
                Thread splashthread = new Thread(new ThreadStart(SplashScreen.ShowSplashScreen));
                splashthread.IsBackground = true;
                splashthread.Start();

                InitializeComponent();
                if (!NetHelper.IsConnectedToInternet)
                {
                    MsgBox.ShowMessage("检测到未连接网络！");
                    this.Close();
                }

                timerAutoChangeProxy.Enabled = false;
                timerAutoChangeProxy.Interval = 1000;
                timerAutoChangeProxy.Elapsed += new System.Timers.ElapsedEventHandler(this.timerAutoChangeProxy_Elapsed);
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
                this.Close();
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            try
            {
                #region 初始化界面
                httpHelper.HttpSetting.Timeout = 60 * 1000;
                this.tsslCountdown.Text = DateTime.Now.ToShortDateString();

                this.tsslAutoChangeProxyStatus.Alignment = ToolStripItemAlignment.Right;
                this.tsslProxyStatus.Alignment = ToolStripItemAlignment.Right;

                this.statusBar.Items.Insert(1, new ToolStripSeparator());
                this.statusBar.Items.Insert(3, new ToolStripSeparator());
                this.statusBar.Items.Insert(5, new ToolStripSeparator());
                this.statusBar.Items.Insert(7, new ToolStripSeparator());
                this.tsslStatus.Spring = true;
                this.tsslVersion.Text = "主程序版本：" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

                this.Text = Application.ProductName + "个人版 v" + Application.ProductVersion;
                #endregion

                #region 初始化配置
                SplashScreen.UpdateStatusText("加载初始配置...");
                GetRssAndNewUrl();
                #endregion

                SplashScreen.UpdateStatusText("加载本地配置...");
                #region 读取本地配置
                //如果存在登录信息文件则读取信息
                if (Config.LocalConfig.IsCooperation && ProxyHelper.GetStartPage(Config.IEStartPage))
                {
                    ProxyHelper.SetStartPage(Config.IEStartPage, true);
                    this.Text = Application.ProductName + "合作版 v" + Application.ProductVersion;
                }
                #endregion

                SplashScreen.UpdateStatusText("加载可用代理...");
                #region 加载可用代理
                FileInfo fi = new FileInfo(Config.ProxyFilePath);
                if (fi.Exists)
                {
                    TxtHelper.ReadAvaliableProxyTxt(Config.ProxyFilePath, Encoding.UTF8);
                }

                if (Config.AvailableProxyData.Rows.Count > 0)
                {
                    Config.ProxyViewForm.dgvProxyList.DataSource = Config.AvailableProxyData;
                    Config.ProxyViewForm.Refresh();
                }
                #endregion

                SplashScreen.UpdateStatusText("加载界面视图...");
                #region 左侧视图
                DockManager = new DockingManager(this, VisualStyle.IDE);

                //定义对象OuterControl，Docking Manager不会关注该对象以后生成的对象的窗口区域
                //对象InnerControl，Docking Manager不会关注在该对象生成以前的对象的窗口区域
                DockManager.OuterControl = statusBar;
                DockManager.InnerControl = tabControlMain;


                #region 可用代理列表视图
                ProxyViewContent = new Content(DockManager);
                ProxyViewContent.Control = Config.ProxyViewForm;
                Size ProxyViewSize = ProxyViewContent.Control.Size;

                ProxyViewContent.Title = "可用代理列表";
                ProxyViewContent.FullTitle = "可用代理列表";
                ProxyViewContent.ImageList = imageList1;
                ProxyViewContent.ImageIndex = 0;
                ProxyViewContent.AutoHideSize = ProxyViewSize;
                ProxyViewContent.DisplaySize = ProxyViewSize;
                ProxyViewContent.HideButton = true;

                //将浮动窗口和具体在浮动窗口中被包含的面板联系起来
                DockManager.Contents.Add(ProxyViewContent);
                WindowContent wcdb = DockManager.AddContentWithState(ProxyViewContent, State.DockLeft);
                #endregion
                #endregion

                SetProxyStatusLabel();

                InitForm();
                this.Show();
                this.tsmiAutoChangeProxy.Text = Config.ProxyViewForm.tsbAutoChangeProxy.Text;
                SplashScreen.CloseSplashScreen();
                this.Activate();
                if (!Config.InitErrorInfo.Equals(""))
                {
                    MsgBox.ShowErrorMessage(Config.InitErrorInfo);
                    this.Close();
                }
                //Thread.Sleep(1000);
                CheckVersionAndDownLoad();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
                this.Close();
            }
        }
        #endregion

        #region Private Methods

        #region  引导起始页
        private  void LoadStartPage()
        {
            SetStatusText("正在加载起始页...");
            AddSinglePage(new frmStartPage(Config.RssUrl), "起始页");
            SetStatusText("就绪");
        }

        #endregion

        private void GetRssAndNewUrl()
        {
            try
            {
                #region Get Config
                string html = httpHelper.GetHtmlNoProxy(Config.GetMainUrl).Replace("\r", "").Replace("\n", "");
                if (html.Contains("ProxyHero"))
                {
                    Regex regex = new Regex(@"<!--&lt;don.yang&gt;(?<ProxyUrl>.+)&lt;/don.yang&gt;");
                    MatchCollection matchs = regex.Matches(html);

                    if (matchs.Count > 0)
                    {
                        string innerHtml = matchs[0].Groups["ProxyUrl"].Value.Trim();

                        regex = new Regex(@"ProxyUrl.+>(?<ProxyUrl>.+)</a>.+/ProxyUrl");
                        MatchCollection matchsHtml = regex.Matches(innerHtml);

                        if (matchsHtml.Count > 0)
                        {
                            Config.ProxyListUrl = matchsHtml[0].Groups["ProxyUrl"].Value;
                            Config.ProxyListUrlOld = Config.ProxyListUrl;
                        }

                        regex = new Regex(@"NewsUrl.+>(?<NewsUrl>.+)</a>.+/NewsUrl");
                        matchsHtml = regex.Matches(innerHtml);

                        if (matchsHtml.Count > 0)
                        {
                            Config.RssUrl = matchsHtml[0].Groups["NewsUrl"].Value;
                        }

                        regex = new Regex(@"StartPage.+>(?<StartPage>.+)</a>.+/StartPage");
                        matchsHtml = regex.Matches(innerHtml);

                        if (matchsHtml.Count > 0)
                        {
                            Config.IEStartPage = matchsHtml[0].Groups["StartPage"].Value;
                        }

                        regex = new Regex(@"StatisticsUrl.+>(?<StatisticsUrl>.+)</a>.+/StatisticsUrl");
                        matchsHtml = regex.Matches(innerHtml);

                        if (matchsHtml.Count > 0)
                        {
                            Config.ProgramStartHomePageUrl = matchsHtml[0].Groups["StatisticsUrl"].Value;
                        }

                        regex = new Regex(@"ShowStatisticsPage.+>(?<ShowStatisticsPage>.+)</a>.+/ShowStatisticsPage");
                        matchsHtml = regex.Matches(innerHtml);

                        if (matchsHtml.Count > 0)
                        {
                            Config.ShowStatisticsPage = matchsHtml[0].Groups["ShowStatisticsPage"].Value;
                        }

                        regex = new Regex(@"ProxyIniUrl.+>(?<ProxyIniUrl>.+)</a>.+/ProxyIniUrl");
                        matchsHtml = regex.Matches(innerHtml);

                        if (matchsHtml.Count > 0)
                        {
                            Config.IniUrl = matchsHtml[0].Groups["ProxyIniUrl"].Value;
                        }

                        regex = new Regex(@"Version&gt;(?<Version>.+)&lt;/Version");
                        matchsHtml = regex.Matches(innerHtml);

                        if (matchsHtml.Count > 0)
                        {
                            Config.NewVersion = matchsHtml[0].Groups["Version"].Value;
                        }

                        regex = new Regex(@"UpdatedEnableUse&gt;(?<UpdatedEnableUse>.+)&lt;/UpdatedEnableUse");
                        matchsHtml = regex.Matches(innerHtml);

                        if (matchsHtml.Count > 0)
                        {
                            Config.UpdatedEnableUse = matchsHtml[0].Groups["UpdatedEnableUse"].Value;
                        }

                        regex = new Regex(@"PopupStartPageWhenExit&gt;(?<PopupStartPageWhenExit>.+)&lt;/PopupStartPageWhenExit");
                        matchsHtml = regex.Matches(innerHtml);

                        if (matchsHtml.Count > 0)
                        {
                            Config.PopupStartPageWhenExit = matchsHtml[0].Groups["PopupStartPageWhenExit"].Value;
                        }
                    }
                    else
                    {
                        SplashScreen.UpdateStatusText("获取网络基础配置失败，请稍后再试！");
                        Config.InitErrorInfo = "获取网络基础配置失败，请稍后再试！";
                    }
                }
                #endregion

                SplashScreen.UpdateStatusText("加载代理配置...");
                #region get ini files

                string iniHtml = httpHelper.GetHtmlNoProxy(Config.IniUrl);
                Config.InitErrorInfo = TxtHelper.WriteTxt(iniHtml, Config.ProxyIniPath, Encoding.Default)[1];

                #region 下载INI
                //DownloadHelper downloadHelper = new DownloadHelper();
                //string today = downloadHelper.iniHelper.read("updateini", "today");
                //TimeSpan ts = new TimeSpan();
                //if (today != "")
                //{
                //    try
                //    {
                //        ts = DateTime.Now - Convert.ToDateTime(today);
                //    }
                //    catch
                //    {
                //    }
                //}

                //if (today == "" || ts.Hours > 6)
                //{
                //    downloadHelper.StrUrl = Config.IniUrl;
                //    downloadHelper.StrFileName = Config.ProxyIniPath;
                //    if (File.Exists(Config.ProxyIniPath))
                //    {
                //        File.Delete(Config.ProxyIniPath);
                //    }

                //    downloadHelper.DownloadFile();

                //    Config.InitErrorInfo = downloadHelper.ErrorInfo;
                //}
                #endregion

                #endregion

                SplashScreen.UpdateStatusText("检查版本信息...");
                #region CheckVersion

                UpdateHelper updateHelper = new UpdateHelper();
                Config.NeedUpdate = updateHelper.CheckVersion();
                #endregion
            }
            catch (System.Net.WebException)
            {
                SplashScreen.UpdateStatusText("初始化失败，请检查网络设置是否正确！");
                Config.InitErrorInfo = "初始化失败，请检查网络设置是否正确！";
            }
            catch (Exception ex)
            {
                SplashScreen.UpdateStatusText("初始化失败！" + ex.Message);
                Config.InitErrorInfo = ex.Message;
            }
        }

        private void CheckVersionAndDownLoad()
        {
            #region update
            if (Config.NeedUpdate)
            {
                if (DialogResult.Yes == MsgBox.ShowQuestionMessage("发现新版本，是否立即更新？"))
                {
                    Process.Start("http://www.loamen.com");
                }
            }

            if (!Config.UpdatedEnableUse.Equals("1") && Config.NeedUpdate)
            {
                if (DialogResult.OK == MsgBox.ShowMessage("此版本已无法使用，请立即更新！"))
                {
                    Process.Start("http://www.loamen.com");
                    Application.Exit();
                }
            }
            #endregion
        }

        #region ClosePage
        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControlMain_ClosePressed(object sender, EventArgs e)
        {
            if (tabControlMain.TabPages.Count > 0)
            {  
                if (tabControlMain.SelectedTab.Control.Name != "frmStartPage")
                {
                    if (!(tabControlMain.SelectedTab.Control.Name == "frmProxy" && this.tsslStatus.Text.Contains("正在")))
                    {
                        OnCloseTabPage(tabControlMain.SelectedTab);
                        tabControlMain.TabPages.Remove(tabControlMain.SelectedTab);
                    }
                }
                if (tabControlMain.TabPages.Count == 0)
                {
                    tabControlMain.Visible = false;
                }
            }
        }

        /// <summary>
        /// 关闭某页时作的处理
        /// </summary>
        /// <param name="page"></param>
        private void OnCloseTabPage(Crownwood.Magic.Controls.TabPage page)
        {
            switch (page.Control.Name)
            {
                case "DbQuery":
                    {
                        //toolBtn_SQLExe.Visible = false;
                        //查询QToolStripMenuItem.Visible = false;
                    }
                    break;
                case "frmIEBrowser":
                    {
                        SetStatusText("就绪");
                        frmIEBrowser frm = (frmIEBrowser)page.Control;
                        Config.WebBrowserArr.Remove(frm.wbMain);
                    }
                    break;
                case "frmProxy":
                    {
                        frmProxy formProxy = (frmProxy)page.Control;
                        formProxy.StopAll();
                    }
                    break;
                case "CodeMaker":
                    {
                    }
                    break;
                case "CodeTemplate":
                    {
                        //toolBtn_Run.Visible = false;
                        //查询QToolStripMenuItem.Visible = false;
                    }
                    break;
                default:
                    SetStatusText("就绪");
                    break;
            }
            page.Control.Dispose();
        }
        #endregion

        private void EnableToolBar(bool enable)
        {
            this.ToolbarMain.Enabled = enable;
            this.MenuMain.Enabled = enable;
            if (enable)
            {
                this.DockManager.ShowAllContents();
            }
            else
            {
                this.DockManager.HideAllContents();
            }
        }

        private void InitForm()
        {
            #region //启动起始页
            DEnableToolBar detb = new DEnableToolBar(this.EnableToolBar);
            try
            {
                this.Invoke(detb, new object[] { false });

                if (!Config.RssUrl.Equals(""))
                {
                    SplashScreen.UpdateStatusText("加载起始页...");
                    LoadStartPage();
                }
                //else
                //{
                //    SplashScreen.UpdateStatusText("加载起始页失败，请检查网络设置是否正确！");
                //    Config.InitErrorInfo = "加载起始页失败，请检查网络设置是否正确！";
                //}
                this.Invoke(detb, new object[] { true });
            }
            catch (System.Net.WebException)
            {
                SplashScreen.UpdateStatusText("初始化失败，请检查网络设置是否正确！");
                Config.InitErrorInfo = "初始化失败，请检查网络设置是否正确！";
            }
            catch (System.Exception ex)
            {
                SplashScreen.UpdateStatusText("初始化失败！" + ex.Message);
                Config.InitErrorInfo = ex.Message;
            }
            #endregion
        }

        private void CheckUpdate()
        {
            #region CheckVersion
            SetStatusText("正在检查更新...");
            string html = httpHelper.GetHtml(Config.GetMainUrl).Replace("\r", "").Replace("\n", "");
            if (html.Contains("ProxyHero"))
            {
                Regex regex = new Regex(@"<!--&lt;don.yang&gt;(?<ProxyUrl>.+)&lt;/don.yang&gt;");
                MatchCollection matchs = regex.Matches(html);

                if (matchs.Count > 0)
                {
                    string innerHtml = matchs[0].Groups["ProxyUrl"].Value.Trim();

                    regex = new Regex(@"Version&gt;(?<Version>.+)&lt;/Version");
                    MatchCollection matchsHtml = regex.Matches(innerHtml);

                    if (matchsHtml.Count > 0)
                    {
                        Config.NewVersion = matchsHtml[0].Groups["Version"].Value;
                    }
                }
            }

            UpdateHelper updateHelper = new UpdateHelper();
            Config.NeedUpdate = updateHelper.CheckVersion();

            Splash.CloseSplash();
            SetStatusText("完毕");
            if (Config.NeedUpdate)
            {
                if (DialogResult.Yes == MsgBox.ShowQuestionMessage("发现新版本是否立即更新?"))
                {
                    Process.Start("http://www.loamen.com");
                }
            }
            else
            {
                MsgBox.ShowMessage("已经是最新版！");
            }
            #endregion
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// 设置状态
        /// </summary>
        /// <param name="text"></param>
        public void SetStatusText(string text)
        {
            this.tsslStatus.Text = text;
        }

        /// <summary>
        /// 创建新的唯一窗体页（不允许重复的）
        /// </summary>
        /// <param name="control"></param>
        /// <param name="Title"></param>
        public void AddSinglePage(Control control, string Title)
        {
            if (tabControlMain.Visible == false)
            {
                tabControlMain.Visible = true;
            }
            bool showed = false;
            Crownwood.Magic.Controls.TabPage currPage = null;
            foreach (Crownwood.Magic.Controls.TabPage page in tabControlMain.TabPages)
            {
                if (page.Control.Name == control.Name)
                {
                    showed = true;
                    currPage = page;
                }
            }
            if (!showed)//不存在
            {
                AddNewTabPage(control, Title);
            }
            else
            {
                tabControlMain.SelectedTab = currPage;
            }
        }

        /// <summary>
        /// 添加新窗体
        /// </summary>
        /// <param name="control"></param>
        /// <param name="Title"></param>
        public void AddNewTabPage(Control control, string Title)
        {
            if (this.tabControlMain.InvokeRequired)
            {
                AddNewTabPageCallback d = new AddNewTabPageCallback(AddNewTabPage);
                this.Invoke(d, new object[] { control, Title });
            }
            else
            {
                Crownwood.Magic.Controls.TabPage page = new Crownwood.Magic.Controls.TabPage();
                page.Title = Title;
                page.Control = control;
                tabControlMain.TabPages.Add(page);
                tabControlMain.SelectedTab = page;
            }
        }

        /// <summary>
        /// 设置当前代理状态
        /// </summary>
        public void SetProxyStatusLabel()
        {
            string[] res = ProxyHelper.GetIEProxy();
            if (res[0] == "1" && res[1] != "")
            {
                string location = "";
                try
                {
                    IpHelper ih = new IpHelper(res[1]);
                    location = " " + ih.Location;
                }
                catch (Exception ex)
                {
                    TxtHelper.WriteLog(ex.Message);
                }
                this.tsslProxyStatus.Text = "当前代理：" + res[1] + location;
                this.tsslProxyStatus.Image = ProxyHero.Properties.Resources.aused;
            }
            else  if (res[0] == "0")
            {
                this.tsslProxyStatus.Text = "当前未使用代理";
                this.tsslProxyStatus.Image = ProxyHero.Properties.Resources.aunuse;
            }
            SetToolTipText(this.tsslProxyStatus.Text);
        }

        public void SetAutoChangeLable(bool enable)
        {
            if (enable)
            {
                this.tsslAutoChangeProxyStatus.Text = "自动切换代理已开启";
                this.tsslAutoChangeProxyStatus.Image = ProxyHero.Properties.Resources.astart;
            }
            else
            {
                this.tsslAutoChangeProxyStatus.Text = "自动切换代理已关闭";
                this.tsslAutoChangeProxyStatus.Image = ProxyHero.Properties.Resources.astop;
                this.tsslCountdown.Text = DateTime.Now.ToShortDateString();
            }
            this.tsslAutoChangeProxyStatus.ToolTipText = this.tsslAutoChangeProxyStatus.Text;
            if (Config.ProxyApplicatioin == "IE")
            {
                SetToolTipText("IE" + this.tsslAutoChangeProxyStatus.Text);
            }
            else
            {
                foreach (WebBrowserEx wbe in Config.WebBrowserArr)
                {
                    wbe.ProxyServer = "";
                }
                SetToolTipText("内置浏览器" + this.tsslAutoChangeProxyStatus.Text);
            }
        }

        /// <summary>
        /// 设置状态栏显示
        /// </summary>
        /// <param name="text"></param>
        public void SetToolTipText(string text)
        {
            this.notifyIconMain.ShowBalloonTip(2000, "提示", text, ToolTipIcon.Info);
        }
        #endregion

        #region Operation
        private void timerAutoChangeProxy_Elapsed(object sender, EventArgs e)
        {
            try
            {
                if (this.timerAutoChangeProxy.Enabled && Config.TsCountDown.TotalMilliseconds > 0)
                {
                    StringBuilder sb = new StringBuilder("下次切换：");
                    if (Config.TsCountDown.Days > 0)
                        sb.Append(Config.TsCountDown.Days + "天");
                    if (Config.TsCountDown.Hours > 0)
                        sb.Append(Config.TsCountDown.Hours + "小时");
                    if (Config.TsCountDown.Minutes > 0)
                        sb.Append(Config.TsCountDown.Minutes + "分");
                    sb.Append(Config.TsCountDown.Seconds + "秒");

                    this.tsslCountdown.Text = sb.ToString();
                    Config.TsCountDown = Config.TsCountDown.Add(new TimeSpan(0, 0, -1));
                }
                else if (this.timerAutoChangeProxy.Enabled && Config.TsCountDown.TotalMilliseconds == 0)
                {
                    this.timerAutoChangeProxy.Stop();
                    AutoChangeHelper aHelper = new AutoChangeHelper();
                    aHelper.ChangeProxy();
                }
                else
                {
                    this.tsslCountdown.Text = DateTime.Now.ToShortDateString();
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void toolBtn_ReadData_Click(object sender, EventArgs e)
        {
            try
            {
                bool hasIt = true;
                if (!this.tsslStatus.Text.Contains("正在验证"))
                {
                    foreach (Crownwood.Magic.Controls.TabPage page in tabControlMain.TabPages)
                    {
                        if (page.Control.Name == "frmProxy")
                        {
                            hasIt = false;
                            tabControlMain.SelectedTab = page;
                            frmProxy formProxy = (frmProxy)page.Control;
                            if (this.toolBtn_ReadData.Text == "读取数据" && !this.tsslStatus.Text.Contains("正在读取"))
                            {
                                formProxy.GetProxyList();
                                this.toolBtn_ReadData.Text = "停止读取";
                                this.toolBtn_ReadData.Image = ProxyHero.Properties.Resources.stop;
                                break;
                            }
                            else if (this.toolBtn_ReadData.Text == "停止读取")
                            {
                                this.tsslStatus.Text = "正在停止...";
                                Splash.StartSplash(this, "正在停止...");
                                formProxy.StopThread();
                                this.toolBtn_ReadData.Text = "读取数据";
                                this.toolBtn_ReadData.Image = ProxyHero.Properties.Resources.run;
                                Splash.CloseSplash();
                                this.tsslStatus.Text = "就绪";
                                break;
                            }
                        }
                    }

                    if (hasIt)
                    {
                        AddSinglePage(new frmProxy(), "代理公布器");
                        toolBtn_ReadData_Click(sender, e);
                    }
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            try
            {
                Application.Exit();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiOption_Click(object sender, EventArgs e)
        {
            try
            {
                frmOption formOption = new frmOption();
                formOption.ShowDialog();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiHomePage_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("http://www.loamen.com");
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiAbout_Click(object sender, EventArgs e)
        {
            try
            {
                frmAboutBox fAbout = new frmAboutBox();
                fAbout.ShowDialog();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void toolBtn_TestAll_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.tsslStatus.Text.Contains("正在读取"))
                {
                    foreach (Crownwood.Magic.Controls.TabPage page in tabControlMain.TabPages)
                    {
                        if (page.Control.Name == "frmProxy")
                        {
                            tabControlMain.SelectedTab = page;
                            frmProxy formProxy = (frmProxy)page.Control;
                            formProxy.TestAll();
                            break;
                        }
                    }

                    Config.ProxyViewForm.BindDataGrid();
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiStop_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (Crownwood.Magic.Controls.TabPage page in tabControlMain.TabPages)
                {
                    if (page.Control.Name == "frmProxy" && this.tsslStatus.Text.Contains("正在验证"))
                    {
                        Splash.StartSplash(this, "正在终止验证...");
                        tabControlMain.SelectedTab = page;
                        frmProxy formProxy = (frmProxy)page.Control;
                        formProxy.StopAll();
                        Splash.CloseSplash();
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                Splash.StartSplash(this,"正在检查更新...");
                this.CheckUpdate();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiCanelProxy_Click(object sender, EventArgs e)
        {
            try
            {
                ProxyHelper proxyHelper = new ProxyHelper();
                proxyHelper.SetIEProxy("", 0);
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiWapBrowser_Click(object sender, EventArgs e)
        {
            try
            {
                ProxyHelper proxyHelper = new ProxyHelper();
                proxyHelper.SetIESupportWap();

                bool hasIt = true;
                foreach (Crownwood.Magic.Controls.TabPage page in tabControlMain.TabPages)
                {
                    if (page.Control.Name == "WAP浏览器")
                    {
                        this.tabControlMain.SelectedTab = page;
                        hasIt = false;
                        break;
                    }
                }

                if (hasIt)
                {
                    Crownwood.Magic.Controls.TabPage page = new Crownwood.Magic.Controls.TabPage();
                    page.Title = "WAP浏览器";
                    frmIEBrowser fomWapBrowser = new frmIEBrowser("http://wap.hao123.com", page);
                    fomWapBrowser.wbMain.UserAgent = "HTC-P4600/1.2 Mozilla/4.0 (compatible; MSIE 6.0; Windows CE; IEMobile 7.11) UP.Link/6.3.1.17.0";
                    Config.WebBrowserArr.Add(fomWapBrowser.wbMain);
                    page.Control = fomWapBrowser;
                    page.Control.Name = "WAP浏览器";
                    this.tabControlMain.TabPages.Add(page);
                    this.tabControlMain.SelectedTab = page;
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (!ProxyHelper.GetStartPage(Config.IEStartPage) && Config.PopupStartPageWhenExit == "1")
                {
                    Process.Start(Config.IEStartPage);
                }
                this.notifyIconMain.Dispose();
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void frmMain_Resize(object sender, EventArgs e)
        {
            try
            {
                if (this.WindowState == FormWindowState.Minimized)
                {
                    this.Hide();
                    //this.notifyIconMain.Visible = true;
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void notifyIconMain_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (this.WindowState == FormWindowState.Normal)
                {
                    this.WindowState = FormWindowState.Minimized;
                }
                else if (this.WindowState == FormWindowState.Minimized)
                {
                    this.Show();
                    this.WindowState = FormWindowState.Normal;
                    //this.notifyIconMain.Visible = false;
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }

        }

        private void tsmiShowMain_Click(object sender, EventArgs e)
        {
            try
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.TopMost = true;
                //this.notifyIconMain.Visible = false;
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Application.Exit();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void gbookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Config.CreateNewIEBrowser("http://bbs.loamen.com", "反馈意见");
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void helpDocumentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Config.CreateNewIEBrowser("http://www.cnblogs.com/mops/articles/1905521.html", "帮助信息");
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiExport_Click(object sender, EventArgs e)
        {
            try
            {
                frmProxy formProxy = null;
                DataTable dt = new DataTable();

                foreach (Crownwood.Magic.Controls.TabPage page in tabControlMain.TabPages)
                {
                    if (page.Control.Name == "frmProxy")
                    {
                        this.tabControlMain.SelectedTab = page;
                        formProxy = (frmProxy)page.Control;
                        break;
                    }
                }

                if (formProxy != null)
                {
                    dt = (DataTable)formProxy.dgvProxyList.DataSource;
                }

                if (dt.Rows.Count > 0)
                {
                    System.Windows.Forms.SaveFileDialog objSave = new System.Windows.Forms.SaveFileDialog();
                    objSave.Filter = "(*.txt)|*.txt|" + "(*.*)|*.*";

                    objSave.FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt";
                    if (objSave.ShowDialog() == DialogResult.OK)
                    {
                        string[] result = TxtHelper.WriteProxyTxt(dt, objSave.FileName, Encoding.UTF8);
                        if (result[1] != "")
                        {
                            MsgBox.ShowErrorMessage(result[1]);
                        }
                    }
                }
                else
                {
                    MsgBox.ShowMessage("没有数据，无法导出！");
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiImport_Click(object sender, EventArgs e)
        {
            try
            {
                if (!tsslStatus.Text.Contains("正在验证"))
                {
                    System.Windows.Forms.OpenFileDialog objOpen = new System.Windows.Forms.OpenFileDialog();
                    objOpen.Filter = "(*.txt)|*.txt|" + "(*.*)|*.*";

                    if (objOpen.ShowDialog() == DialogResult.OK)
                    {
                        string[] result = TxtHelper.ReadProxyTxt(objOpen.FileName, Encoding.UTF8);

                        if (result[1] != "")
                        {
                            MsgBox.ShowErrorMessage(result[1]);
                        }
                        else
                        {
                            bool hasIt = true;
                            foreach (Crownwood.Magic.Controls.TabPage page in tabControlMain.TabPages)
                            {
                                if (page.Control.Name == "frmProxy")
                                {
                                    hasIt = false;
                                    break;
                                }
                            }

                            if (hasIt)
                            {
                                Splash.StartSplash(this, "正在导入数据...");
                                frmProxy formProxy = new frmProxy();
                                AddSinglePage(formProxy, "代理公布器");
                                formProxy.BindDgv(Config.ProxyData);
                                Splash.CloseSplash();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.tsslStatus.Text.Contains("正在验证"))
                {
                    DataTable dt = Config.ProxyData.Copy();
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr["Speed"].ToString() == "888888")
                        {
                            Config.ProxyData.Rows.Remove(Config.ProxyData.Rows.Find(new object[] { dr["IP"], dr["Port"] }));
                        }
                    }

                    bool hasIt = true;
                    foreach (Crownwood.Magic.Controls.TabPage page in tabControlMain.TabPages)
                    {
                        if (page.Control.Name == "frmProxy")
                        {
                            hasIt = false;
                            break;
                        }
                    }

                    if (hasIt)
                    {
                        frmProxy formProxy = new frmProxy();
                        AddSinglePage(formProxy, "代理公布器");
                        formProxy.BindDgv(Config.ProxyData);
                    }

                    SetStatusText("共" + Config.ProxyData.Rows.Count + "条");
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiCancelProxy_Click(object sender, EventArgs e)
        {
            try
            {
                ProxyHelper proxyHelper = new ProxyHelper();
                proxyHelper.SetIEProxy("", 0);
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        public void tsmiViewProxyList_Click(object sender, EventArgs e)
        {
            try
            {
                bool hasIt = true;
                foreach (Crownwood.Magic.Controls.TabPage page in tabControlMain.TabPages)
                {
                    if (page.Control.Name == "frmProxy")
                    {
                        this.tabControlMain.SelectedTab = page;
                        hasIt = false;
                        break;
                    }
                }

                if (hasIt)
                {
                    frmProxy formProxy = new frmProxy();
                    AddSinglePage(formProxy, "代理公布器");
                    formProxy.BindDgv(Config.ProxyData);
                }

                SetStatusText("共" + Config.ProxyData.Rows.Count + "条");
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsslCountdown_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right && Config.AutoProxyQueue.Count > 0)
                {
                    frmAutoChangeQueue fcq = new frmAutoChangeQueue();
                    fcq.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiStartAutoChange_Click(object sender, EventArgs e)
        {
            try
            {
                Config.ProxyViewForm.SetAutoChange();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void cmsRightMenu_VisibleChanged(object sender, EventArgs e)
        {
            try
            {
                this.tsmiAutoChangeProxy.Text = Config.ProxyViewForm.tsbAutoChangeProxy.Text;
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiViewAvaliableProxySideBar_Click(object sender, EventArgs e)
        {
            try
            {
                Content content = DockManager.Contents["可用代理列表"];
                if (this.tsmiViewAvaliableProxySideBar.Checked)
                {
                    DockManager.HideContent(content);
                }
                else
                {
                    DockManager.ShowContent(content);
                }
                this.tsmiViewAvaliableProxySideBar.Checked = !this.tsmiViewAvaliableProxySideBar.Checked;
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiViewTestProxy_Click(object sender, EventArgs e)
        {
            try
            {
                #region 验证代理视图
                if (ProxyTestContent == null)
                {
                    ProxyTestContent = new Content(DockManager);
                    ProxyTestContent.Control = Config.TestProxyForm;
                    Size ProxyTestSize = ProxyTestContent.Control.Size;

                    ProxyTestContent.Title = "验证代理";
                    ProxyTestContent.FullTitle = "验证代理";
                    ProxyTestContent.ImageList = imageList1;
                    ProxyTestContent.ImageIndex = 1;
                    ProxyTestContent.AutoHideSize = ProxyTestSize;
                    ProxyTestContent.DisplaySize = ProxyTestSize;
                    ProxyTestContent.HideButton = true;

                    //将浮动窗口和具体在浮动窗口中被包含的面板联系起来
                    DockManager.Contents.Add(ProxyTestContent);
                    DockManager.AddContentWithState(ProxyTestContent, State.DockRight);
                }
                #endregion

                Content content = DockManager.Contents["验证代理"];
                if (this.tsmiViewTestProxy.Checked)
                {
                    DockManager.HideContent(content);
                }
                else
                {
                    DockManager.ShowContent(content);
                }
                this.tsmiViewTestProxy.Checked = !this.tsmiViewTestProxy.Checked;
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }
        #endregion   

        private void tsmiCheckIPArea_Click(object sender, EventArgs e)
        {
            try
            {
                frmCheck formCheck = new frmCheck(this.tsmiCheckIPArea.Text);
                formCheck.ShowDialog();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiCheckAnonymous_Click(object sender, EventArgs e)
        {
            try
            {
                frmCheck formCheck = new frmCheck(this.tsmiCheckAnonymous.Text);
                formCheck.ShowDialog();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiBrowser_Click(object sender, EventArgs e)
        {
            try
            {
                Config.CreateNewIEBrowser("about:blank");
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsmiUpdateLog_Click(object sender, EventArgs e)
        {
            try
            {
                Config.CreateNewIEBrowser("http://www.cnblogs.com/mops/articles/1664774.html", "更新日志");
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void tsbAddBrowser_Click(object sender, EventArgs e)
        {
            try
            {
                Config.CreateNewIEBrowser("about:blank");
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }
    }
}
